﻿using System;
using System.Data.Services.Client;
using System.Diagnostics;
using System.Linq;
using Azure.Toolkit;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.StorageClient;
using SimplePoll.Web.Models;

namespace SimplePoll.Web.DataAccess
{
    public class PollRepository
    {
        readonly CloudStorageAccount account;

        public PollRepository()
        {
            account = CloudConfiguration.GetStorageAccount("DataConnectionString");
        }

        public Poll Retrieve()
        {
            var context = new PollDataContext(account) {MergeOption = MergeOption.NoTracking};
            // we only have one poll so we will get the latest
            var query = context.Polls.Take(1).AsTableServiceQuery();

            return query.Execute().SingleOrDefault();
        }

        public Poll Retrieve(string name)
        {
            var context = new PollDataContext(account) {MergeOption = MergeOption.NoTracking};

            var query = (from poll in context.Polls
                         where poll.PartitionKey == name.Encode()
                         select poll).AsTableServiceQuery();
            return query.Execute().SingleOrDefault();
        }

        public void Save(Poll poll)
        {
            var context = new PollDataContext(account);

            try
            {
                var repo = new Azure.Toolkit.Azure.TableRepository<Poll>();
                repo.Insert(poll);
                repo.Commit();

            }
            catch (InvalidOperationException ex)
            {
                Delete(poll);
                Trace.TraceError(ex.TraceInformation());
                throw;
            }
        }

        void Delete(Poll poll)
        {
            if (poll == null)
                return;
           
            var pollToDelete = Retrieve(poll.Name);
            var context = new PollDataContext(account);
            context.DeleteObject(pollToDelete);
            context.SaveChanges();
        }
    }
}